#ifndef MODELVIEWWIDGET_H
#define MODELVIEWWIDGET_H

#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLBuffer>
#include <QOpenGLShaderProgram>
#include <QOpenGLVertexArrayObject>
#include "modelloader.h"
#include "log.h"

#define DEBUG_MODEL_VIEW_WIDGET false

class ModelViewWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
    Q_OBJECT

public:
    explicit ModelViewWidget(QString path, QWidget *parent = 0);
    ~ModelViewWidget();

    QSize minimumSizeHint() const override;
    QSize sizeHint() const override;
    void setModelAttitude(float pitch, float roll, float yaw);
    void getCameraPosition(float &x, float &y, float &z);

signals:
    void clicked();

protected:
    void initializeGL() override;
    void paintGL() override;
    void resizeGL(int width, int height) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;

private:

    QColor clearColor;
    QPoint lastPosMouse;

    void createShaderProgram();// 生成着色器
    void createBuffers();// 读取模型，生成buffer
    void createAttributes();// buffer的映射
    void setupLightingAndMatrices();

    void drawNode(const Node *node, QMatrix4x4 objectMatrix);
    void setMaterialUniforms(MaterialInfo &mater);

    // 渲染模型
    QOpenGLShaderProgram m_shaderProgram;
    QOpenGLVertexArrayObject m_vao;
    QOpenGLBuffer m_vertexBuffer;
    QOpenGLBuffer m_normalBuffer;
    QOpenGLBuffer m_textureUVBuffer;
    QOpenGLBuffer m_indexBuffer;

    // 模型位置、姿态
    float x, y, z;
    float m_pitch, m_roll, m_yaw;
    // 观察点/相机的位置
    float camerax, cameray, cameraz;

    // 绘制坐标平面
    QOpenGLShaderProgram m_shaderProgramCoordinatePlanes;
    QOpenGLVertexArrayObject m_vaoCoordinatePlanes;
    QOpenGLBuffer m_coordinatePlanesBuffer;
    float *pointsCoordinatePlanes;
    int pointsNumCoordinatePlanes;
    int createCoordinatePlanesPoints(float length, int lineNum);

    QSharedPointer<Node> m_rootNode;

    QMatrix4x4 m_projection, m_view, m_model;

    QString m_filepath;
    QString m_texturePath;

    LightInfo m_lightInfo;
    MaterialInfo m_materialInfo;

    bool m_error;
};

#endif
